package com.hmyd.hmyd_android.ui;

import java.math.BigDecimal;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.hmyd.hmyd_android.AppBasic;
import com.hmyd.hmyd_android.R;
import com.hmyd.hmyd_android.commons.UrlConstant;
import com.hmyd.hmyd_android.dto.Investment;
import com.hmyd.hmyd_android.utils.PreferencesUtils;
import com.hmyd.hmyd_android.utils.Utils;
import com.hmyd.hmyd_android.view.HomeSeekArc;
import com.hmyd.hmyd_android.view.TriangleRateView;
import com.lidroid.xutils.http.RequestParams;
import com.lidroid.xutils.http.client.HttpRequest.HttpMethod;
import com.lidroid.xutils.view.annotation.ContentView;
import com.lidroid.xutils.view.annotation.ViewInject;
import com.lidroid.xutils.view.annotation.event.OnClick;

/**
 * 项目详情页
 * @author Administrator
 *
 */
@ContentView(R.layout.activity_investment_detail)
public class InvestmentDetailActivity extends BasicActivity implements OnClickListener {
	@ViewInject(R.id.home_title)
	public View home_title;
	@ViewInject(R.id.home_title_txt)
	public TextView home_title_txt;
	@ViewInject(R.id.home_right)
	public TextView home_right;
	
	@ViewInject(R.id.investment_description)
	private View mInvestmentDescription;
	@ViewInject(R.id.investment_history)
	private View mInvestmentHistory;
	@ViewInject(R.id.now_investment)
	private Button mNowInvestment;

	private static String SER_KEY = "SER_KEY";

	private Investment investment;
//	 private Capital capital;

	@ViewInject(R.id.type)
	private TextView type;
	@ViewInject(R.id.title)
	private TextView title;
	@ViewInject(R.id.interest_rate)
	private TextView investment_rate;
	@ViewInject(R.id.interest_rate_sp)
	private TextView investment_rate_sp;
	@ViewInject(R.id.time)
	private TextView time;
	@ViewInject(R.id.progress_layout)
	private TextView progress_layout;
	@ViewInject(R.id.seekArc)
	private HomeSeekArc seekArc;
	@ViewInject(R.id.minInvestAmount)
	private TextView minInvestAmount;
	@ViewInject(R.id.enable_amount)
	private TextView enable_amount;
	@ViewInject(R.id.invest_total_account)
	private TextView total;
	
	@ViewInject(R.id.countdown_layout)
	private View mCountdownLayout;
	@ViewInject(R.id.h)
	private TextView mH;
	@ViewInject(R.id.m)
	private TextView mM;
	@ViewInject(R.id.s)
	private TextView mS;
	
	@ViewInject(R.id.introduce)
	private View introduce;
	@ViewInject(R.id.tag)
	private TextView tag;
	@ViewInject(R.id.assetsdetail_guide)
	private ImageView assetsdetail_guide;

	long l;
	long hour;
	long min;
	long s;
	
	@ViewInject(R.id.triangle)
	private TriangleRateView triangle;
	
	private boolean isCountdown = false;

	Handler handler = new Handler();
	Runnable runnable = new Runnable() {
		int p = 0;

		@Override
		public void run() {

			isCountdown = true;

			mH.setText(hour + "");
			mM.setText(min + "");
			mS.setText(s + "");

			if (l >= 1000) {
				l = l - 1000;

				hour = (l / (60 * 60 * 1000));
				min = ((l / (60 * 1000)) - hour * 60);
				s = (l / 1000 - hour * 60 * 60 - min * 60);

				if (p == 100) {
					p = 0;
				} else {
					p++;
				}
			} else {
				p = 0;

				mNowInvestment.setVisibility(View.VISIBLE);
				mNowInvestment.setOnClickListener(InvestmentDetailActivity.this);
				mNowInvestment.setText("立即投资");

				mCountdownLayout.setVisibility(View.VISIBLE);

				l = investment.endTime - AppBasic.ServerTime;
			}

			handler.postDelayed(this, 1000);
		}
	};

	final Handler handlerStop = new Handler() {
		public void handleMessage(Message msg) {
			switch (msg.what) {
			case 1:
				isCountdown = false;
				handler.removeCallbacks(runnable);
				break;
			}
			super.handleMessage(msg);
		}
	};

	private final int GET = 1;
	private final int CAPITAL = 2;
	private final int INVESTMENT = 3;

	public static Intent getIntent(Context context, Investment investment) {
		Intent intent = new Intent(context, InvestmentDetailActivity.class);
		Bundle mBundle = new Bundle();
		mBundle.putSerializable(SER_KEY, investment);
		intent.putExtras(mBundle);

		return intent;
	}

	public static Intent getIntent(Context context, String investmentId) {
		Intent intent = new Intent(context, InvestmentDetailActivity.class);
		intent.putExtra("investmentId", investmentId);

		return intent;
	}


	@Override
	protected void onResume() {
		super.onResume();

		String investmentId = getIntent().getStringExtra("investmentId");

		if (investment != null) {
			RequestParams params = new RequestParams();
			params.addBodyParameter("itemId", investment.id);

			onRequest(GET, UrlConstant.ITEMDETAIL, HttpMethod.GET, params);
		} else if (!TextUtils.isEmpty(investmentId)) {
			RequestParams params = new RequestParams();
			params.addBodyParameter("itemId", investmentId);

			onRequest(GET, UrlConstant.ITEMDETAIL, HttpMethod.GET, params);
		}
	}

	private void setData(Investment investment) {
		if (investment != null) {
			title.setText(investment.title);
			
			/**
			 * 年化利率图计算
			 */
			double rt = 0;
			String rate = investment.rate;
			
			getRateView(investment);
			
			rt = getRateLast(rate);
			
			triangle.setName(new String[]{"银行存款","存钱罐","银行理财","国泰惠民益贷"});
			if (AppBasic.app != null && 
					!TextUtils.isEmpty(AppBasic.app.BackRates) &&
					!TextUtils.isEmpty(AppBasic.app.SavingPot) &&
					!TextUtils.isEmpty(AppBasic.app.BankFinancing)) {
				triangle.setRate(new double[]{
						getRate(AppBasic.app.BackRates), 
						getRate(AppBasic.app.SavingPot), 
						getRate(AppBasic.app.BankFinancing), 
						rt});
			} else {
				triangle.setRate(new double[]{3.12, 4.6, 5.26, rt});
			}
			
			// 设置活动标签
			if (!TextUtils.isEmpty(investment.itemtagIcon)
					&& !TextUtils.isEmpty(investment.itemTagName)
					&& !TextUtils.isEmpty(investment.itemTagUrl)) {
				introduce.setVisibility(View.VISIBLE);
				introduce.setTag(investment.itemTagUrl);
				tag.setText(investment.itemTagName);
			} else {
				introduce.setVisibility(View.GONE);
			}
			
			if (investment.type.equals("shf")) {
				type.setText("首惠丰");
				type.setTextColor(getResources().getColor(R.color.text_orange));
				
				type.setBackgroundDrawable(getResources().getDrawable(R.drawable.shape_shf_bg));
			} else if (investment.type.equals("phb")) {
				type.setText("普惠保");
				type.setTextColor(getResources().getColor(R.color.pro_type_txt));

				type.setBackgroundDrawable(getResources().getDrawable(R.drawable.shape_pu_bg));
			} else if (investment.type.equals("hht")) {
				type.setText("鸿惠通");
				type.setTextColor(getResources().getColor(R.color.holo_red_dark));

				type.setBackgroundDrawable(getResources().getDrawable(R.drawable.shape_hht_bg));
			} else {
				type.setText("");
			}

//			interest_rate.setText(investment.rate);
			time.setText("投资期限：  "+investment.period + Utils.periodConversion(investment.periodUnit));
			progress_layout.setText(Integer.valueOf(investment.progress)+"%\n投资进度");

			total.setText(Utils.amountConversionFormat(Double.valueOf(investment.totalAmount)));

			seekArc.setProgress(Integer.valueOf(investment.progress), false);
			seekArc.setTouchEnable(false);
			
			minInvestAmount.setText(Utils.amountConversionFormat(Double
					.parseDouble(investment.minInvestAmount)));
			
			mNowInvestment.setBackgroundResource(R.color.text_orange);
			mNowInvestment.setEnabled(true);

			if ("invest".equals(investment.itemStatus)) {
				mCountdownLayout.setVisibility(View.VISIBLE);

				l = investment.endTime - AppBasic.ServerTime;

				if (!isCountdown) {
					handler.postDelayed(runnable, 0);
				}
			}

			if ("full".equals(investment.itemStatus) || "repay".equals(investment.itemStatus)
					|| "success".equals(investment.itemStatus)) {
				mNowInvestment.setEnabled(false);
				mNowInvestment.setText("已被抢光");
				mNowInvestment.setBackgroundResource(R.color.text_gray);

				mCountdownLayout.setVisibility(View.INVISIBLE);
			}

			if ("reserve".equals(investment.itemStatus)) {
				mNowInvestment.setEnabled(false);
				mNowInvestment.setText("敬请期待");
				mNowInvestment.setOnClickListener(null);
				mNowInvestment.setBackgroundResource(R.color.text_gray);

				mCountdownLayout.setVisibility(View.VISIBLE);

				l = investment.startTime - AppBasic.ServerTime;

				if (!isCountdown) {
					handler.postDelayed(runnable, 0);
				}
			}

			if ("order".equals(investment.itemStatus)) {
				mNowInvestment.setText("立即预约");
				mNowInvestment.setBackgroundResource(R.color.text_orange);
				mNowInvestment.setOnClickListener(this);

				mCountdownLayout.setVisibility(View.VISIBLE);

				l = investment.startTime - AppBasic.ServerTime;

				if (!isCountdown) {
					handler.postDelayed(runnable, 0);
				}
			}

			double purchasedAmount = Double.valueOf(investment.purchasedAmount);
			double totalAmount = Double.valueOf(investment.totalAmount);

			enable_amount.setText(Utils.amountConversionFormat(totalAmount - purchasedAmount));
		}
	}
	
	/**
	 * 将字符串转换成Double类型
	 * @param rate
	 * @return
	 */
	public double getRate(String rate){
		double rt = 0 ;
		if (rate.contains("%")) {
			rt = Double.parseDouble(rate.replace("%", ""));
		}
		return rt;
	}
	
	public double getRateLast(String rate){
		try {
			rate = rate.contains("%") ? rate.replace("%", "") : rate;
			
			if(rate.contains("+")) {
				String[] r = rate.split("[+]");
				return sum(Double.parseDouble(r[0].trim()), Double.parseDouble(r[1].trim()));
			} else {
				return Double.parseDouble(rate);
			}
		} catch (Exception e) {
			Utils.printException(e);
		}
		return 0;
	}
	
	/**
	 * 获取利率
	 * @param investment
	 * @param holder
	 */
	private void getRateView(Investment investment){
		String rate_value = investment.rate;
		String rate = "";
		String rate_sp = "";

		// 如果包含%， 删除所有%  手动添加
		rate_value = rate_value.contains("%") ? rate_value.replace("%", "") : rate_value;

		if (rate_value.contains("+")) {
			rate = rate_value.split("[+]")[0];
			rate_sp = rate_value.split("[+]")[1];

			investment_rate.setText(rate);
			investment_rate_sp.setText("% + "+rate_sp+"%");
		} else {
			investment_rate_sp.setVisibility(View.GONE);
			
			investment_rate.setText(rate_value + "%");
		}
	}
	
	/**
     * double 相加
     * @param d1
     * @param d2
     * @return
     */
    public double sum(double d1,double d2){
        BigDecimal bd1 = new BigDecimal(Double.toString(d1));
        BigDecimal bd2 = new BigDecimal(Double.toString(d2));
        return bd1.add(bd2).doubleValue();
    }

	public void onPostSuccess(int postId, String result) {
		Gson gson = new Gson();
		switch (postId) {
		case GET:
			java.lang.reflect.Type type2 = new TypeToken<Investment>() {
			}.getType();
			investment = gson.fromJson(result, type2);

			setData(investment);
			break;
		default:
			break;
		}

	}

	@OnClick({R.id.img_calculator, R.id.now_investment, R.id.investment_history, R.id.investment_description, R.id.introduce,R.id.assetsdetail_guide})
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.img_calculator:
			Intent intent = new Intent(this, CalculatorActivity.class);
			intent.putExtra("rate", Double.toString(getRateLast(investment.rate)));
			intent.putExtra("period", investment.period);
			startActivity(intent);
			break;
		case R.id.now_investment:

			if (AppBasic.isLogin) {
				startActivity(ConfirmInvestmentActivity.getIntent(InvestmentDetailActivity.this,
						investment.id, investment.type, investment.title, investment.rate,
						String.valueOf(investment.period), investment.periodUnit, 0,
						investment.endTime, investment.itemStatus, investment.baseAmount,
						investment.minInvestAmount, investment.totalAmount,
						investment.purchasedAmount));
			} else {
				startActivity(new Intent(InvestmentDetailActivity.this, LoginActivity.class));
			}

			break;

		case R.id.investment_history:
			startActivity(InvestmentHistoryActivity.getIntent(this, investment.id,false,""));
			break;
		case R.id.investment_description:
			startActivity(InvestmentDescriptionActivity.getIntent(this, investment.id));
			break;
		case R.id.introduce:
			String url = v.getTag().toString();
			Utils.jumpURL(InvestmentDetailActivity.this, url, "活动介绍", "", false);
			break;
		case R.id.assetsdetail_guide:
			assetsdetail_guide.setVisibility(View.GONE);
			PreferencesUtils.putBoolean(this, PreferencesUtils.getIsFirstAssetsDetail(this), false);
			break;
		default:
			break;
		}
	}

	@Override
	public void onDestroy() {
		super.onDestroy();

		if (handlerStop != null && handler != null && runnable != null) {
			Message message = new Message();
			message.what = 1;
			handlerStop.sendMessage(message);
		}
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		if (requestCode == INVESTMENT && resultCode == RESULT_OK) {

			setResult(RESULT_OK);
			finish();
		}
	}

	@Override
	protected void setParams() {
		home_title_txt.setText(getString(R.string.title_investment_detail));
		home_title.setOnTouchListener(touch);
		

		investment = (Investment) getIntent().getSerializableExtra(SER_KEY);

		setData(investment);
		
		if (PreferencesUtils.getBoolean(this, PreferencesUtils.getIsFirstAssetsDetail(this), true)) {
			assetsdetail_guide.setVisibility(View.VISIBLE);
		}
	}

	@Override
	protected void leftButton() {
		AppBasic.getInstance().finishCurrentActivity();
	}

	@Override
	protected void rightButton() {
		
	}

	@Override
	public void onPostFailure(int postId, String msg) {
		
	}

}
